import 'dart:ffi';

import 'package:clock_notification/pages/picture/scan.dart';
import 'package:date_format/date_format.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../config/const_config.dart';
import '../../config/text_input_format.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../picture/pdf.dart';

class CardNavigator extends StatelessWidget {
  final String title;
  final List iconTitle;

  const CardNavigator(
      {super.key, required this.title, required this.iconTitle});

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 1170.w,
        height: 610.h,
        color: ConstConfig.cardColorNo,
        child: Card(
          margin: const EdgeInsets.all(10),
          // color: ConstConfig.cardColor,
          elevation: 3,
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(20),
                alignment: Alignment.bottomLeft,
                color: ConstConfig.cardColorNo,
                child: Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              // Line
              const Divider(
                height: 1.0,
                indent: 20.0,
                endIndent: 0.0,
                color: ConstConfig.dividerColor,
              ),
              Expanded(
                  child: Container(
                color: ConstConfig.cardColorNo,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: iconTitle.map((e) {
                    return GestureDetector(
                      onTap: e["func"],
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [e["image"], Text(e["title"])],
                      ),
                    );
                  }).toList(),
                ),
              ))
            ],
          ),
        ));
  }
}

class WaitSubmit extends StatefulWidget {
  final String title;

  const WaitSubmit({super.key, required this.title});

  @override
  State<WaitSubmit> createState() => _WaitSubmitState();
}

// 待提交页面
class _WaitSubmitState extends State<WaitSubmit> {
  // 减免额度
  final double deductionAmount = 10.0;

  // 首付
  double downPayments = 0;

  bool autofocus = true;

  // 生效日期开始
  DateTime effectiveDateStart = DateTime(2024, 1, 1);
  DateTime effectiveDateEnd = DateTime(2025, 1, 1);
  final TextEditingController _downPaymentsController = TextEditingController();

  final FocusNode _downPaymentsFocusNode = FocusNode();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _downPaymentsController.dispose();
    _downPaymentsFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          width: 1170.w,
          height: 610.h,
          // color: ConstConfig.cardColorNo,
          child: Card(
            margin: const EdgeInsets.all(10),
            color: Colors.white,
            // shape: const CircleBorder(side: BorderSide(width: 10)),
            elevation: 3,
            child: Column(
              children: [
                // Container(
                //   padding: const EdgeInsets.all(20),
                //   alignment: Alignment.centerLeft,
                //   // color: ConstConfig.cardColorNo,
                //   child: Text(
                //     title,
                //     style: const TextStyle(
                //       fontSize: 16,
                //       fontWeight: FontWeight.normal,
                //     ),
                //   ),
                // ),
                TextField(
                  decoration: const InputDecoration(
                      labelText: "首付比例",
                      labelStyle: TextStyle(fontSize: 20),
                      hintText: "请输入首付比例",
                      border: OutlineInputBorder()),
                  controller: _downPaymentsController,
                  focusNode: _downPaymentsFocusNode,
                  inputFormatters: [
                    // FilteringTextInputFormatter.allow(RegExp(r'[0-9.]'))//设置只允许输入数字
                    FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true),
                    MyNumberTextInputFormatter(digit: 2),
                  ],
                  keyboardType: TextInputType.number,
                  onChanged: (String val) {
                    print("val $val");
                    if (val != "") {
                      setState(() {
                        downPayments = double.parse(val);
                      });
                    }
                  },
                  onSubmitted: (String value) {
                    print("回车 $value");
                    setState(() {
                      downPayments = double.parse(value);
                    });
                  },
                  onTapOutside: (PointerDownEvent event) {
                    print("onTapOutside");
                    setState(() {
                      downPayments = double.parse(_downPaymentsController.text);
                      FocusScope.of(context).requestFocus(FocusNode());
                    });
                  },
                  autofocus: autofocus,
                ),
                // Line
                const Divider(
                  height: 1.0,
                  indent: 20.0,
                  endIndent: 0.0,
                  color: ConstConfig.dividerColor,
                ),
                Container(
                    alignment: Alignment.centerLeft,
                    color: ConstConfig.transparentColor,
                    padding: const EdgeInsets.all(20),
                    child: Text(
                      "自动计算减免额度: $deductionAmount",
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.normal,
                      ),
                    )),
                const Divider(
                  height: 1.0,
                  indent: 20.0,
                  endIndent: 0.0,
                  color: ConstConfig.dividerColor,
                ),
                Expanded(
                    child: Container(
                        // height: 200.h,
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.only(left: 20),
                        color: ConstConfig.transparentColor,
                        child: Row(
                          children: [
                            const Text("生效日期:"),
                            OutlinedButton(
                              child: Text(buildEffectiveRange(
                                  effectiveDateStart, effectiveDateEnd)),
                              onPressed: () async {
                                Locale myLocale = const Locale('zh');
                                final currentDate = DateTime.now();
                                final lastDate =
                                    currentDate.add(const Duration(days: 1000));
                                DateTimeRange? _dateRangeTime =
                                    await showDateRangePicker(
                                        context: context,
                                        firstDate: currentDate,
                                        lastDate: lastDate,
                                        locale: myLocale,
                                        saveText: "保存");

                                if (_dateRangeTime != null) {
                                  setState(() {
                                    effectiveDateStart = _dateRangeTime.start;
                                    effectiveDateEnd = _dateRangeTime.end;
                                  });
                                }
                                print(_dateRangeTime);
                              },
                            )
                          ],
                        ))),
              ],
            ),
          ),
        ),
        downPayments < 10
            ? const PictureSelectCard(title: "残疾证、重大疾病证明", maxPicNum: 3)
            : const SizedBox(
                height: 0,
              ),
        const SizedBox(
          height: 10,
        ),
        downPayments < 10
            ? const PictureSelectCard(title: "身份证", maxPicNum: 2)
            : const SizedBox(
                height: 0,
              ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Expanded(
                child: TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              style: ElevatedButton.styleFrom(
                  // shape: ,
                  side: const BorderSide(color: Colors.grey),
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.white,
                  shadowColor: Colors.black),
              child: const Text(
                "暂存",
                style: TextStyle(color: Colors.black),
              ),
            )),
            Expanded(
                child: TextButton(
                    onPressed: () {},
                    style: ElevatedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.blue),
                    child: const Text("提交")))
          ],
        ),
        // const PdfViewerCard()
      ],
    );
  }
}

// 审核中card
class WaitReview extends StatelessWidget {
  final String title;

  // 减免额度
  final double deductionAmount = 10.0;

  // 首付
  final double downPayments = 100;

  // 生效日期开始
  final DateTime effectiveDateStart = DateTime(2024, 1, 1);
  final DateTime effectiveDateEnd = DateTime(2025, 1, 1);

  WaitReview({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
        ),
        width: 1170.w,
        height: 610.h,
        // color: ConstConfig.cardColorNo,
        child: Card(
          margin: const EdgeInsets.all(10),
          color: Colors.white,
          // shape: const CircleBorder(side: BorderSide(width: 10)),
          elevation: 3,
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(20),
                alignment: Alignment.centerLeft,
                // color: ConstConfig.cardColorNo,
                child: Text(
                  title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ),
              // Line
              const Divider(
                height: 1.0,
                indent: 20.0,
                endIndent: 0.0,
                color: ConstConfig.dividerColor,
              ),
              Container(
                  alignment: Alignment.centerLeft,
                  color: ConstConfig.transparentColor,
                  padding: const EdgeInsets.all(20),
                  child: Text(
                    "自动计算减免额度:  $deductionAmount",
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.normal,
                    ),
                  )),
              const Divider(
                height: 1.0,
                indent: 20.0,
                endIndent: 0.0,
                color: ConstConfig.dividerColor,
              ),
              Expanded(
                  child: Container(
                      // height: 200.h,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.only(left: 20),
                      color: ConstConfig.transparentColor,
                      child: Text(
                        "生效日期:  ${buildEffectiveRange(effectiveDateStart, effectiveDateEnd)}",
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.normal,
                        ),
                      ))),
            ],
          ),
        ));
  }
}

String buildEffectiveRange(
    DateTime effectiveDateStart, DateTime effectiveDateEnd) {
  if (effectiveDateStart == null || effectiveDateEnd == null) {
    return "";
  }
  return "${formatDate(effectiveDateStart, [
        yyyy,
        '年',
        mm,
        '月',
        dd
      ])}  - ${formatDate(effectiveDateEnd, [yyyy, '年', mm, '月', dd])}";
}

// 图片选择框
class PictureSelectCard extends StatefulWidget {
  final String title;
  final int maxPicNum;

  const PictureSelectCard(
      {super.key, required this.title, required this.maxPicNum});

  @override
  State<PictureSelectCard> createState() => _PictureSelectCardState();
}

class _PictureSelectCardState extends State<PictureSelectCard> {
  List<AssetEntity> seriousList = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      // color: Colors.red,
      width: double.infinity,
      margin: const EdgeInsets.only(left: 10, right: 10),
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
      decoration: const BoxDecoration(
          //背景
          color: Color.fromRGBO(0xFF, 0xFF, 0xFF, 1.0),
          //设置四周圆角 角度
          borderRadius: BorderRadius.all(Radius.circular(8.0)),
          //设置四周边框
          // border: Border.all(width: 2, color: Colors.red),
          boxShadow: [
            BoxShadow(
                // color: Color.fromRGBO(0xAA, 0xB2, 0x43, 1.0), blurRadius: 1.0),
                color: Colors.grey,
                blurRadius: 5.0),
          ]),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 10, right: 10),
            child: Text(
              widget.title,
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
            ),
          ),
          const SizedBox(
            height: 15.0,
          ),
          Container(
              width: double.infinity,
              height: 200.h,
              margin: const EdgeInsets.only(left: 10, right: 10),
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                //背景
                // color: Colors.red,
                //设置四周圆角 角度
                borderRadius: BorderRadius.all(Radius.circular(8.0)),
                // border: Border.all(width: 2, color: Colors.red,
                //     style:BorderStyle.solid),
                //设置四周边框
                // border: Border.all(width: 2, color: Colors.red),
              ),
              child: GestureDetector(
                onTap: () async {
                  final List<AssetEntity>? result =
                      await AssetPicker.pickAssets(context,
                          pickerConfig: AssetPickerConfig(maxAssets: widget.maxPicNum));
                  // print(result?.length);
                  if (result!.isNotEmpty) {
                    setState(() {
                      seriousList = result;
                    });
                  }
                },
                child: DottedBorder(
                  borderType: BorderType.RRect,
                  color: Colors.grey,
                  dashPattern: const [4, 4, 4, 4],
                  radius: const Radius.circular(12),
                  // padding: EdgeInsets.all(30),
                  child: const SizedBox(
                    width: double.infinity,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.photo_camera_outlined,
                          size: 30,
                        ),
                        Text(
                          "选择图片",
                          style: TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 12),
                        ),
                        // Wrap(
                        //   children: seriousList.map((e) => AssetEntityImage(
                        //       asset,
                        //       width: 50,
                        //       height: 50,
                        //     )).toList(),
                        // )
                      ],
                    ),
                  ),
                ),
              )),
          // LayoutBuilder(builder: (context, constraints) {
          //   final double width  =  constraints.maxWidth - 20;
          Container(
            width: double.infinity,
            height: 200.h,
            margin: const EdgeInsets.only(left: 10, right: 10),
            // alignment: Alignment.centerRight,
            decoration: const BoxDecoration(
              //背景
              // color: Colors.red,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(8.0)),
              // border: Border.all(width: 2, color: Colors.red,
              //     style:BorderStyle.solid),
              //设置四周边框
              // border: Border.all(width: 2, color: Colors.red),
            ),
            // width: double.infinity,
            // height: 200.h,
            // margin: const EdgeInsets.only(left: 10, right: 10),
            // alignment: Alignment.center,
            // direction: Axis.horizontal,
            // spacing: 10,
            // alignment: WrapAlignment.spaceEvenly,
            child: Row(
              children: seriousList.isNotEmpty
                  ? seriousList
                      .map(
                        (e) => GestureDetector(
                            onTap: () {
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (context) => PictureScan(
                                      initialIndex: seriousList.indexOf(e),
                                      items: seriousList)));
                            },
                            child: AssetEntityImage(
                              e,
                              height: 50,
                              width: 50,
                              fit: BoxFit.cover,
                            )),
                      )
                      .toList()
                  : [
                      const SizedBox(
                        height: 0,
                      )
                    ],
            ),
          )
        ],
      ),
    );
  }
}
